/**
 * Created by henian.xu on 2018/8/24.
 * 只为 解决 微信6.7.4 ios12 软键盘收回时页面不回弹
 * 微信 bug 修复后应该 删除
 */
import Vue from 'vue';
import Router from 'router';
import { changeOldRouteUrl, isUrl } from 'utils/index';

let inFocus = false;
const isIosWx = (() => {
  const ua = navigator.userAgent.toLowerCase();
  const u = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

  if (`${ua.match(/MicroMessenger/i)}` === 'micromessenger' && !!u) {
    return true;
  }
  return false;
})();

function temporaryRepair() {
  // console.log(222, inFocus)
  let currentPosition;
  const speed = 1; // 页面滚动距离
  const timer = setInterval(() => {
    currentPosition =
      document.documentElement.scrollTop || document.body.scrollTop;
    currentPosition -= speed;
    window.scrollTo(0, currentPosition); // 页面向上滚动
    currentPosition += speed; // speed变量
    window.scrollTo(0, currentPosition); // 页面向下滚动
    clearInterval(timer);
  }, 1);
}
function checkWxScroll() {
  // console.log(111, inFocus)
  if (isIosWx) {
    setTimeout(() => {
      if (!inFocus) temporaryRepair();
    }, 200);
  }
}

Vue.directive('reset-input', {
  inserted(el) {
    el.__reset_input_focus = () => {
      inFocus = true;
    };
    el.__reset_input_blur = () => {
      inFocus = false;
      checkWxScroll();
    };

    el.addEventListener('focus', el.__reset_input_focus);
    el.addEventListener('blur', el.__reset_input_blur);
  },
  unbind(el) {
    el.removeEventListener('focus', el.__reset_input_focus);
    delete el.__reset_input_focus;
    el.removeEventListener('blur', el.__reset_input_blur);
    delete el.__reset_input_blur;
  },
});
function findATag(el, root) {
  while (el) {
    const tagName = (el.tagName || '').toLocaleLowerCase();
    if (tagName !== 'a') {
      el = el.parentElement;
      if (el === root) return null;
    } else {
      return el;
    }
  }
  return null;
}
function handleRichTextClick(event) {
  const target = findATag(event.target, this);
  if (!target) return;
  const href = target.getAttribute('href');
  if (isUrl(href)) return;
  let path = changeOldRouteUrl(href);
  // if (path === href) return;
  // event.stopPropagation();
  event.preventDefault();
  path = path.replace(/^#/, '');
  Router.push(path);
  // console.dir(target);
  // console.log(href, path, target.outerHTML);
}
Vue.directive('rich-text-link', {
  inserted(el) {
    el.addEventListener('click', handleRichTextClick);
  },
  unbind(el) {
    el.removeEventListener('click', handleRichTextClick);
  },
});
